<template>
  <el-dialog
      :title="props.type == 'add' ? '添加分类' : '修改分类'"
      v-model="state.visible"
      width="600px"

  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
      <el-form-item label="公告标题" prop="title">
        <el-input type="text" v-model="state.ruleForm.title"></el-input>
      </el-form-item>


      <el-form-item label="内容" prop="content">
        <el-input type="text" v-model="state.ruleForm.content"></el-input>
      </el-form-item>
    </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
      </template>



  </el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useRoute} from 'vue-router'
import {getAnnouncementById,addAnnouncement,updateAnnouncement} from '../service/announcementApi.js'
import  { uploadImgServer } from  "../store/index.js"
import {ElMessage} from 'element-plus'

const props = defineProps({
  type: String, // 用于判断是添加还是编辑
  reload: Function // 添加或修改完后，刷新列表页
})
const formRef = ref(null)
const route = useRoute()
const filelist =ref([])
const state = reactive({

  visible: false,
  categoryLevel: 1,
  parentId: 0,
  ruleForm: {
    id: '',
    title: '',
    content:''
  },
  rules: {

    title: [
      { required: true, message: '名称不能为空', trigger: ['change'] }
    ],
    content: [
      { required: true, message: '内容不能为空', trigger: ['change'] }
    ],

  },
})
// 获取详情
const getDetail = async (id) => {
  const result = await getAnnouncementById(id);
  // 回显表单数据
  state.ruleForm = {
    id: result.data.id,
    title: result.data.title,
    content:result.data.content,

  }
}


// 开启弹窗
const open = (id) => {
  state.visible = true
  if (id) {
    state.ruleForm.id = id
    // 如果是有 id 传入，证明是修改模式
    getDetail(id)
  } else {
    // 否则为新增模式
    // 新增类目，从路由获取分类 level 级别和父分类 id

    const {level = 1, parent_id = 0} = route.query
    state.ruleForm = {
      id: '',
      title: '',
      content:''
    }
    state.parentId = parent_id
    state.categoryLevel = level
  }
}
// 关闭弹窗
const close = () => {
  state.visible = false
}
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.type === 'add') {
        // 添加方法
        await addAnnouncement(state.ruleForm).then(() => {
          ElMessage.success('添加成功')
          close()
          if (props.reload) props.reload()
        })
      } else {
        // 修改方法
        await updateAnnouncement(state.ruleForm).then(() => {
          ElMessage.success('修改成功')
          close()
          if (props.reload) props.reload()
        })
      }
    }
  })
}
defineExpose({open, close})
</script>

<style scoped>

</style>